#include "CoffBucket.h"
#include <iostream>
#include "Log.h"

using namespace std;

CCoffBucket::CCoffBucket( int size )
{
	m_iMaxSize = size;
	m_pvecCoffList = new vector<CCoffItem*>();
}

CCoffBucket::~CCoffBucket()
{
	for( vector<CCoffItem*>::iterator i=m_pvecCoffList->begin(); i!=m_pvecCoffList->end(); i++ )
	{
		delete *i;
	}
	delete m_pvecCoffList;
}

bool CCoffBucket::Insert( CCoffItem * item )
{

	if ( FindDuplication( item->coff ) )
	{
		return false;
	}

	vector<CCoffItem*>::iterator iter = m_pvecCoffList->begin();
	bool find = false;
	for( ; iter != m_pvecCoffList->end(); iter++ )
	{
		if ( (*iter)->psnr < item->psnr )
		{
			find = true;
			break;
		}
	}


	if ( find )
	{
		CCoffItem * new_item = new CCoffItem( item->coff, item->psnr );
		// find the insert point
		m_pvecCoffList->insert( iter, new_item );
		if ( m_pvecCoffList->size() > (unsigned int)m_iMaxSize )
		{
			CCoffItem * item = (*m_pvecCoffList)[m_pvecCoffList->size()-1];
			delete item;
			m_pvecCoffList->pop_back();
		}

	}
	else
	{
		// at the end of the list
		if ( m_pvecCoffList->size() == m_iMaxSize )
		{
			// the list is full, can't add any more.
			return false;
		}
		else
		{
			// add to the last position of the list
			CCoffItem * new_item = new CCoffItem( item->coff, item->psnr );
			m_pvecCoffList->push_back( new_item );
		}
	}

	return true;
}

void CCoffBucket::Dump()
{
	CLog * log = CLog::GetInstance();
	log->log_stream << "=== Dump Bucket " << endl;
	log->log_stream << "Bucket Size: " << m_pvecCoffList->size() << endl;

	log->log_stream << "Bucket: " << endl;;
	for ( unsigned int i=0; i<m_pvecCoffList->size(); i++ )
	{
		log->log_stream << "PSNR: " << (*m_pvecCoffList)[i]->psnr << "; COFF: ";
		for ( int j=0; j<REF_PIXEL_NUMBER; j++ )
		{
			log->log_stream << (int) (*m_pvecCoffList)[i]->coff[j] << "; ";
		}
		log->log_stream << endl;
		break;
	
	}

	log->log_stream << endl;
}



bool CCoffBucket::FindDuplication( char * coff )
{
	for ( unsigned int i=0; i<m_pvecCoffList->size(); i++ )
	{
		if ( memcmp( coff, (*m_pvecCoffList)[i]->coff, sizeof(char) * REF_PIXEL_NUMBER ) == 0 )
		{
			return true;
		}
	}

	return false;
}